package com.rui.patterns.singleton.demo07;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @className    : Client
 * @author       : [锐神NO.3]
 * @version      : [v1.0]
 * @createTime   : [2022/2/9 12:03]
 * @description  : [描述该类的功能]
 */
 
public class Client {
    public static void main(String[] args) throws Exception {
//        writeObjectToFile();
        readObjectFromFile();
        readObjectFromFile();
    }

    /**
     * 向文件中写数据
     */
    public static void writeObjectToFile() throws Exception{
        //1.获取Singleton对象
        Singleton singleton = Singleton.getInstance();

        //定义文件所在位置
        String path = "D:\\StudyProject\\IdeaProject\\design_patterns\\src\\main\\java\\com\\rui\\patterns\\singleton\\demo07\\file\\a.txt";

        //2.创建对象输出流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));

        //3.将对象写入文件
        oos.writeObject(singleton);

        //4.释放资源
        oos.close();
    }

    /**
     * 从文件中读取数据
     */
    public static void readObjectFromFile() throws Exception{
        //1.创建对象输入流对象

        //2.从文件中读取对象
        String path = "D:\\StudyProject\\IdeaProject\\design_patterns\\src\\main\\java\\com\\rui\\patterns\\singleton\\demo07\\file\\a.txt";
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));

        //3.获取对象
        Singleton instance = (Singleton) objectInputStream.readObject();
        System.out.println(instance);

        //4.释放资源
        objectInputStream.close();
    }
}
